﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using Sinacor.Infra.Common.Security.Cryptography;

namespace RegistryConfiguration
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        List<Key> allowedKeys = new List<Key>();

        const string localRoot = "HKEY_LOCAL_MACHINE";
        const string subkey = "SOFTWARE";
        const string sinacorKey = "SINACOR";
        const string dataKey = "Infra.Data";
        const string keyName = localRoot + "\\" + subkey + "\\" + sinacorKey + "\\" + dataKey + "\\";

        #region Constructor
        public Window1()
        {
            this.SetResourceReference(StyleProperty, "ControlWindow");

            CommandBindings.Add(new CommandBinding(SinacorWindowCommands.Minimize, btnMinimize_Click));
            //CommandBindings.Add(new CommandBinding(SinacorWindowCommands.Maximize, btnMaximize_Click));
            CommandBindings.Add(new CommandBinding(SinacorWindowCommands.Restore, btnRestore_Click));
            CommandBindings.Add(new CommandBinding(SinacorWindowCommands.Close, btnClose_Click));

            InitializeComponent();
            Inicializar();
        }

        private void Inicializar()
        {
            allowedKeys.Add(Key.Tab);
            allowedKeys.Add(Key.D0);
            allowedKeys.Add(Key.D1);
            allowedKeys.Add(Key.D2);
            allowedKeys.Add(Key.D3);
            allowedKeys.Add(Key.D4);
            allowedKeys.Add(Key.D5);
            allowedKeys.Add(Key.D6);
            allowedKeys.Add(Key.D7);
            allowedKeys.Add(Key.D8);
            allowedKeys.Add(Key.D9);
            allowedKeys.Add(Key.NumPad0);
            allowedKeys.Add(Key.NumPad1);
            allowedKeys.Add(Key.NumPad2);
            allowedKeys.Add(Key.NumPad3);
            allowedKeys.Add(Key.NumPad4);
            allowedKeys.Add(Key.NumPad5);
            allowedKeys.Add(Key.NumPad6);
            allowedKeys.Add(Key.NumPad7);
            allowedKeys.Add(Key.NumPad8);
            allowedKeys.Add(Key.NumPad9);
            allowedKeys.Add(Key.Back);
            allowedKeys.Add(Key.Delete);
            allowedKeys.Add(Key.Right);
            allowedKeys.Add(Key.Left);
            allowedKeys.Add(Key.Up);
            allowedKeys.Add(Key.Down);
            allowedKeys.Add(Key.Home);
            allowedKeys.Add(Key.End);
            allowedKeys.Add(Key.Insert);
            allowedKeys.Add(Key.LeftCtrl);
            allowedKeys.Add(Key.LeftShift);
            allowedKeys.Add(Key.RightCtrl);
            allowedKeys.Add(Key.RightShift);

        }
        #endregion

        #region Minimize/Maximize
        protected void btnMinimize_Click(object sender, EventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }

        protected void btnMaximize_Click(object sender, EventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Maximized;

        }
        #endregion

        #region Restore/Close
        protected void btnRestore_Click(object sender, EventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Normal;
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        #endregion

        #region KeyPress - Just Numbers
        private void TxtMaxPoolSize_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!allowedKeys.Contains(e.Key))
                e.Handled = true;
        }

        private void TxtMinPoolSize_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!allowedKeys.Contains(e.Key))
                e.Handled = true;
        }

        private void TxtTimeout_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (!allowedKeys.Contains(e.Key))
                e.Handled = true;
        }
        #endregion

        #region Window Loaded
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            GetRegistryValues();
        }
        #endregion

        #region GetRegistryValues
        private void GetRegistryValues()
        {
            // Busca Max Pool Size
            if (!String.IsNullOrEmpty(Convert.ToString(Registry.GetValue(keyName, "MaxPoolSize", ""))))
                TxtMaxPoolSize.Text = Registry.GetValue(keyName, "MaxPoolSize", "").ToString();

            // Busca Min Pool Size
            if (!String.IsNullOrEmpty(Convert.ToString(Registry.GetValue(keyName, "MinPoolSize", ""))))
                TxtMinPoolSize.Text = Registry.GetValue(keyName, "MinPoolSize", "").ToString();

            // Busca TimeOut
            if (!String.IsNullOrEmpty(Convert.ToString(Registry.GetValue(keyName, "TimeOut", ""))))
                TxtTimeOut.Text = Registry.GetValue(keyName, "TimeOut", "").ToString();

            // Busca User
            if (!String.IsNullOrEmpty(Convert.ToString(Registry.GetValue(keyName, "User", ""))))
                TxtUser.Text = Registry.GetValue(keyName, "User", "").ToString();

            // Busca Pooling
            if (!String.IsNullOrEmpty(Convert.ToString(Registry.GetValue(keyName, "Pooling", ""))))
                chkPooling.IsChecked = Convert.ToBoolean(Registry.GetValue(keyName, "Pooling", false).ToString());

            // Busca Instance
            if (!String.IsNullOrEmpty(Convert.ToString(Registry.GetValue(keyName + "Instances", "Default", ""))))
                TxtInstance.Text = Registry.GetValue(keyName + "Instances", "Default", "").ToString();

            // Busca Encrypted
            if (Convert.ToString(Registry.GetValue(keyName + "Config", "IsEncrypted", "0")) != "0" && Convert.ToString(Registry.GetValue(keyName + "Config", "IsEncrypted", "0")) != "")
                chkEncriptado.IsChecked = true;


        }
        #endregion

        #region MaskConnectionString
        static private string MaskConnectionString(String connectionString)
        {
            if (connectionString == null)
                throw new ArgumentNullException("connectionString");

            SymmetricCryptographer.Algorithm algorithm = new SymmetricCryptographer.Algorithm();
            byte[] key = { 15, 54, 6, 17, 38, 25, 80, 41 };
            byte[] maskedConnectionString = null;
            byte[] unmaskedConnectionString = null;
            string maskedConnection = "";

            ProtectedKey protectedKey = ProtectedKey.Create(key);
            SymmetricCryptographer cryptographer = new SymmetricCryptographer(algorithm, protectedKey);

            //string para bytes
            unmaskedConnectionString = Encoding.Unicode.GetBytes(connectionString);


            //Criptografa
            maskedConnectionString = cryptographer.Encrypt(unmaskedConnectionString);

            //bytes para string
            maskedConnection = Convert.ToBase64String(maskedConnectionString);

            return maskedConnection;
        }
        #endregion

        #region Button Save
        private void BtnSalvar_Click(object sender, RoutedEventArgs e)
        {
            bool savePassword = false;

            // Verificação de Password
            if (!String.IsNullOrEmpty(TxtPassword.Password) || !String.IsNullOrEmpty(TxtRepeticao.Password))
            {
                if (String.IsNullOrEmpty(TxtPassword.Password))
                {
                    MessageBox.Show("Digite a Senha!","Mensagem",MessageBoxButton.OK,MessageBoxImage.Error);
                    TxtPassword.Focus();
                    return;
                }

                if (String.IsNullOrEmpty(TxtRepeticao.Password))
                {
                    MessageBox.Show("Digite a Repetição da Senha!", "Mensagem", MessageBoxButton.OK, MessageBoxImage.Error);
                    TxtRepeticao.Focus();
                    return;
                }

                if (TxtPassword.Password != TxtRepeticao.Password)
                {
                    MessageBox.Show("A Repetição da Senha não confere!", "Mensagem", MessageBoxButton.OK, MessageBoxImage.Error);
                    TxtRepeticao.Focus();
                    return;
                }

                savePassword = true;
            }

            // Salva Max Pool Size
            Registry.SetValue(keyName, "MaxPoolSize", TxtMaxPoolSize.Text);

            // Salva Min Pool Size
            Registry.SetValue(keyName, "MinPoolSize", TxtMinPoolSize.Text);

            // Salva TimeOut
            Registry.SetValue(keyName, "TimeOut", TxtTimeOut.Text);

            // Salva User
            Registry.SetValue(keyName, "User", TxtUser.Text);

            // Salva Pooling
            Registry.SetValue(keyName, "Pooling", chkPooling.IsChecked.ToString().ToLower());

            // Salva Instance
            Registry.SetValue(keyName + "Instances", "Default", TxtInstance.Text);

            // Salva Encrypted
            if (chkEncriptado.IsChecked.Value)
                Registry.SetValue(keyName + "Config", "IsEncrypted", "1");
            else
                Registry.SetValue(keyName + "Config", "IsEncrypted", "0");

            //Salva Password
            if (savePassword)
            {
                Registry.SetValue(keyName, "Password", MaskConnectionString(TxtPassword.Password));
            }

            MessageBox.Show("Configurações realizadas com Sucesso!", "Mensagem", MessageBoxButton.OK, MessageBoxImage.Exclamation);

        }
        #endregion

        #region OnApplyTemplate
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            System.Windows.Controls.Grid Header1 = this.GetTemplateChild("Header1") as System.Windows.Controls.Grid;
            Header1.MouseLeftButtonDown += new MouseButtonEventHandler(headerArea_MouseLeftButtonDown);

            System.Windows.Controls.Grid Header2 = this.GetTemplateChild("Header2") as System.Windows.Controls.Grid;
            Header2.MouseLeftButtonDown += new MouseButtonEventHandler(headerArea_MouseLeftButtonDown);

            System.Windows.Controls.Grid Header3 = this.GetTemplateChild("Header3") as System.Windows.Controls.Grid;
            Header3.MouseLeftButtonDown += new MouseButtonEventHandler(headerArea_MouseLeftButtonDown);
        }

        void headerArea_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        #endregion

    }
}
